﻿using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.NetworkAnalysis;
using ESRI.ArcGIS.Output;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TubeBurstAnalysis
{
    public partial class FormAnalysis : Form
    {

        /// <summary>
        /// 目标阀门列表
        /// </summary>
        public List<IFeature> listTargetValves;

        /// <summary>
        /// 失灵阀门列表
        /// </summary>
        public List<IFeature> listFaultyValves;

        /// <summary>
        /// 主窗体地图默认控件
        /// </summary>
        private IMapControlDefault mapControlDefault;
        public IMapControlDefault MapControlDefault
        {
            set => mapControlDefault = value;
        }

        /// <summary>
        /// 主窗体地图控件
        /// </summary>
        private AxMapControl axMapControl;

        public AxMapControl AxMapControl
        {
            set => axMapControl = value;
        }

        /// <summary>
        /// 阀门属性Map，key为Name，Value为中文名
        /// </summary>
        public Dictionary<string, string> propMap;

        /// <summary>
        /// 显示的阀门属性Map，key为Name，Value为中文名
        /// </summary>
        public Dictionary<string, string> shownPropMap;

        /// <summary>
        /// 当前进行分析的几何网络
        /// </summary>
        public IGeometricNetwork geometricNetwork;

        /// <summary>
        /// 执行网络追踪分析所使用的接口
        /// </summary>
        public ITraceFlowSolverGEN traceFlowSolverGEN;

        /// <summary>
        /// 进行网络追踪分析所使用的另一接口
        /// </summary>
        public INetSolver netSolver;

        /// <summary>
        /// 爆管管道列表
        /// </summary>
        public List<IEdgeFlag> listEdgeFlags;

        /// <summary>
        /// 管点列表(仅作为参数)
        /// </summary>
        public List<IJunctionFlag> listJunctionFlags;

        /// <summary>
        /// 爆管点列表（用于绘制地图元素）
        /// </summary>
        private readonly List<IPoint> burstPoints;

        /// <summary>
        /// 主窗体的axPageLayout控件
        /// </summary>
        public AxPageLayoutControl axPageLayoutControl;

        /// <summary>
        /// listBox中显示的目标阀门列表
        /// </summary>
        private readonly List<IShownValve> shownTargetValves;

        /// <summary>
        /// listBox中显示的故障阀门列表
        /// </summary>
        private readonly List<IShownValve> shownFaultyValves;

        /// <summary>
        /// 爆管点的地点
        /// </summary>
        private readonly List<string> addressList;

        /// <summary>
        /// 图像宽度
        /// </summary>
        public int imgWidth = 560;

        /// <summary>
        /// 图像高度
        /// </summary>
        public int imgHeight = 560;


        public FormAnalysis()
        {
            InitializeComponent();
            shownFaultyValves = new List<IShownValve>();
            shownTargetValves = new List<IShownValve>();
            burstPoints = new List<IPoint>();
            addressList = new List<string>();
            Show();
            dataGridView1.Focus();
            //生成属性中英文映射
            generatePropMap();
            shownPropMap = new Dictionary<string, string>(propMap);
        }

        /// <summary>
        /// 根据阀门列表生成listBox显示信息以及地图图标
        /// </summary>
        public void start()
        {
            shownTargetValves.Clear(); //清空显示目标阀门数据
            //遍历目标阀门数据，根据IFeature对象生成IShownValve对象，添加到listBox1绑定的列表中
            for (int i = 0; i < listTargetValves.Count; i++)
            {
                IShownValve targetValve = new IShownValve(listTargetValves[i]);
                shownTargetValves.Add(targetValve);
            }
            listBox1.DisplayMember = "Name";
            BindingSource bs = new BindingSource
            {
                DataSource = shownTargetValves
            };
            listBox1.DataSource = bs;

            //遍历失灵阀门数据，根据IFeature对象生成IShownValve对象，添加到listBox2绑定的列表中
            shownFaultyValves.Clear();
            for (int i = 0; i < listFaultyValves.Count; i++)
            {
                IShownValve faultyValve = new IShownValve(listFaultyValves[i]);
                shownFaultyValves.Add(faultyValve);
            }
            listBox2.DisplayMember = "Name";
            BindingSource bs1 = new BindingSource
            {
                DataSource = shownFaultyValves
            };
            listBox2.DataSource = bs1;

            //渲染阀门
            renderValves(listFaultyValves);
            renderValves(listTargetValves);

            //根据shownTargetValves和shownFaultyValves生成显示数据
            generateDataGridView();

        }

        /// <summary>
        /// 选择阀门改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            //获取选择的阀门要素
            IShownValve shownTargetValve = (IShownValve)listBox1.SelectedValue;
            IFeature feature = shownTargetValve.feature;

            //feature为空则返回
            if (feature == null)
            {
                return;
            }

            //获取阀门要素的外形、包络线
            IGeometry geometry = feature.Shape;
            IEnvelope envelope = geometry.Envelope;


            //对geometry的包络线进行扩张
            if (geometry.GeometryType != esriGeometryType.esriGeometryPoint)
            {
                envelope.Expand(1.5, 1.5, true);
            }
            else
            {
                envelope.Expand(200, 200, false);
            }

            //修改地图当前显示内容到阀门包络线
            mapControlDefault.Extent = envelope;
            mapControlDefault.ActiveView.Refresh();
        }

        /// <summary>
        /// 获取文件夹
        /// </summary>
        /// <returns>选择的文件夹路径</returns>
        private string GetFolderPath()
        {
            string folderPath = string.Empty;
            using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
            {
                //对话框的标题
                folderBrowserDialog.Description = "选择文件夹";
                //显示对话框
                DialogResult dialogResult = folderBrowserDialog.ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    //获取选择的文件夹的路径
                    folderPath = folderBrowserDialog.SelectedPath;
                }
            };
            return folderPath;
        }


        /// <summary>
        /// 移动视图到指定元素集
        /// </summary>
        /// <param name="features"></param>
        private void moveToFeatures(List<IFeature> features)
        {
            if (features == null || features.Count == 0)
            {
                MessageBox.Show("请先执行爆管分析");
                return;
            }
            //获取选择的阀门要素
            IFeature feature = features[0];

            //feature为空则返回
            if (feature == null)
            {
                return;
            }

            //获取阀门要素的外形、包络线
            IGeometry geometry = feature.Shape;
            IEnvelope envelope = geometry.Envelope;
            envelope.Expand(10, 10, false);

            for (int i = 1; i < features.Count; i++)
            {
                //获取阀门要素的外形、包络线
                IEnvelope envelopei = new EnvelopeClass();
                envelopei.Union(features[i].Shape.Envelope);
                envelopei.Expand(60, 60, false);
                //联合
                envelope.Union(envelopei);
            }

            //修改地图当前显示内容到阀门包络线
            mapControlDefault.Extent = envelope;
            mapControlDefault.ActiveView.Refresh();
        }

        private void listBox2_SelectedValueChanged(object sender, EventArgs e)
        {
            //获取选择的阀门要素
            IShownValve shownTargetValve = (IShownValve)listBox2.SelectedValue;
            IFeature feature = shownTargetValve.feature;

            //feature为空则返回
            if (feature == null)
            {
                return;
            }

            //获取阀门要素的外形、包络线
            IGeometry geometry = feature.Shape;
            IEnvelope envelope = geometry.Envelope;

            //检查当前地图编号
            //MessageBox.Show(feature.get_Value(feature.Fields.FindField("Map_No")).ToString()); ;

            //对geometry的包络线进行扩张
            if (geometry.GeometryType != esriGeometryType.esriGeometryPoint)
            {
                envelope.Expand(1.5, 1.5, true);
            }
            else
            {
                envelope.Expand(200, 200, false);
            }

            //修改地图当前显示内容到阀门包络线
            mapControlDefault.Extent = envelope;
            mapControlDefault.ActiveView.Refresh();

        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            try
            {
                #region 文件信息设置
                //文件名
                string fileName = Guid.NewGuid() + "爆管分析结果.PDF";

                string ImageName = Guid.NewGuid() + "当前显示区域.JPEG";

                //获取文件位置
                string folderPath = GetFolderPath() + "\\";

                //设置文件路径
                string filePath = folderPath + fileName;

                string imagePath = folderPath + ImageName;
                #endregion

                #region 获取图片

                //调整视图以显示所有阀门
                moveToFeatures(listTargetValves);
                DrawBurstPipePoint(axMapControl.ActiveView, "BurstPipePoint", burstPoints);//绘制爆管点
                updatePageLayout();
                //输出图片前向pageLayout中插入标题,比例尺
                //InsertTitle(axPageLayoutControl);//插入标题
                AddScalebar(axPageLayoutControl);//插入比例尺
                //输出图片
                ExportMapToImage(axPageLayoutControl, imagePath); //输出axPageLayoutControl控件中的图片

                #endregion

                #region 字体设置
                //字体
                BaseFont simhei = BaseFont.CreateFont(@"C:/Windows/Fonts/SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                Font simheiFont = new Font(simhei)
                {
                    Color = BaseColor.BLACK,
                    Size = 13f
                };

                BaseFont midhei = BaseFont.CreateFont(@"C:/Windows/Fonts/SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                Font midheiFont = new Font(midhei)
                {
                    Color = BaseColor.BLACK,
                    Size = 16f
                };

                BaseFont bighei = BaseFont.CreateFont(@"C:/Windows/Fonts/SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                Font bigheiFont = new Font(bighei)
                {
                    Color = BaseColor.BLACK,
                    Size = 20f
                };

                BaseFont bighei2 = BaseFont.CreateFont(@"C:/Windows/Fonts/SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                Font bighei2Font = new Font(bighei2)
                {
                    Color = BaseColor.BLACK,
                    Size = 25f
                };

                BaseFont littlehei = BaseFont.CreateFont(@"C:/Windows/Fonts/SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                Font littleheiFont = new Font(littlehei)
                {
                    Color = BaseColor.BLACK,
                    Size = 5f
                };

                BaseFont simkai = BaseFont.CreateFont(@"C:/Windows/Fonts/simkai.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                Font simkaiFont = new Font(simkai);
                #endregion

                #region 创建PDF
                //创建PDF
                Document document = new Document(PageSize.A4, 20, 20, 30, 0);

                PdfWriter pdfWriter = PdfWriter.GetInstance(document, new System.IO.FileStream(filePath, FileMode.Create));

                document.Open();
                document.NewPage();
                document.SetMargins(20, 20, 30, 0);
                #endregion

                #region 标题
                StringBuilder titleBuilder = new StringBuilder();
                for (int i = 0; i < addressList.Count; i++)
                {
                    if (i != addressList.Count - 1)
                    {
                        titleBuilder.Append(addressList[i] + ',');
                    }
                    else
                    {
                        titleBuilder.Append(addressList[i]);
                    }
                }
                titleBuilder.Append("燃气管网爆管分析结果");
                Paragraph title = new Paragraph(titleBuilder.ToString(), bighei2Font); ;
                title.Alignment = Element.ALIGN_CENTER;
                document.Add(title);
                document.Add(new Phrase("\r\n", simkaiFont));
                document.Add(new Phrase("\r\n", simkaiFont));
                #endregion



                #region 向文件中添加图片               
                Paragraph message = new Paragraph("待关闭阀门位置概览:", bigheiFont);
                message.Alignment = Element.ALIGN_LEFT; 
                document.Add(message);
                document.Add(new Phrase("\r\n", simkaiFont));
                document.Add(new Phrase("\r\n", littleheiFont));

                // 插入图标题
                Paragraph titlePage = new Paragraph("待关阀门位置概览图", midheiFont);
                titlePage.Alignment = Element.ALIGN_CENTER;
                document.Add(titlePage);

                // 插入图片
                Image image = Image.GetInstance(imagePath);
                image.ScaleToFit(imgWidth*1.5f, imgHeight*1.5f);
                image.Alignment = 1;
                document.Add(image);
                document.Add(new Phrase("\r\n", simkaiFont));
                #endregion

                #region 信息
                Paragraph message1 = new Paragraph("待关阀门以及失灵阀门信息:", bigheiFont)
                {
                    Alignment = Element.ALIGN_LEFT
                };
                document.Add(message1);
                document.Add(new Phrase("\r\n", littleheiFont));

                //创建表格
                PdfPTable table = new PdfPTable(dataGridView1.Columns.Count)
                {
                    TotalWidth = 560,
                    LockedWidth = true
                };
                for (int i = 0; i < dataGridView1.Columns.Count; i++)
                {
                    table.AddCell(new Phrase(dataGridView1.Columns[i].HeaderText.ToString(), simkaiFont));
                }

                table.HeaderRows = 1;

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        try
                        {
                            table.AddCell(new Phrase(dataGridView1.Rows[i].Cells[j].Value.ToString(), simkaiFont));
                        }
                        catch
                        {
                        }
                    }
                }

                document.Add(table);


                //分隔
                document.Add(new Phrase("\r\n", simkaiFont));
                //document.Add(new Phrase("\r\n", simkaiFont));
                #endregion

                #region 日期&单位

                //日期
                Paragraph date = new Paragraph(System.DateTime.Today.ToString(), simkaiFont)
                {
                    Alignment = Element.ALIGN_RIGHT
                };
                document.Add(date);

                //部门
                Paragraph dept = new Paragraph("××地下管道分析中心", simkaiFont)
                {
                    Alignment = Element.ALIGN_RIGHT
                };
                document.Add(dept);

                #endregion

                //关闭
                document.Close();
                //删除图片
                File.Delete(imagePath);
                try
                {
                    //打开PDF
                    System.Diagnostics.Process.Start(filePath);
                }
                catch
                {
                    MessageBox.Show("分析结果输出成功！");
                }
            }
            catch
            {

            }


        }

        /// <summary>
        /// pageLayout输出图片
        /// </summary>
        /// <param name="pageLyaoutCtrl">地图布局控件</param>
        /// <returns></returns>
        private void ExportMapToImage(AxPageLayoutControl pageLyaoutCtrl, string imagePath)
        {
            try
            {
                //文件名
                string ImageName = Guid.NewGuid() + "当前显示区域.JPEG";

                // 获取布局视图屏幕分辨率，用于设置输出分辨率
                double iScreenDispalyResolution = pageLyaoutCtrl.ActiveView.ScreenDisplay.DisplayTransformation.Resolution;
                // 导出为图片类型
                IExport pExport = new ExportJPEGClass
                {
                    // 设置输出文件名，为用户在保存窗口设置的文件名
                    ExportFileName = imagePath,
                    // 设置输出分辨率
                    Resolution = 400 //400像素
                };
                // 获取输出范围  获取视图框架对象，进而得到视图范围
                tagRECT deviceRect = pageLyaoutCtrl.ActiveView.ScreenDisplay.DisplayTransformation.get_DeviceFrame();

                imgWidth = deviceRect.right - deviceRect.left;
                imgHeight = deviceRect.bottom - deviceRect.top;

                deviceRect.right = deviceRect.left + imgWidth * 4;
                deviceRect.bottom = deviceRect.top + imgHeight * 4;

                IEnvelope pDeviceEnvelop = new EnvelopeClass();
                // 设置一个边框范围
                pDeviceEnvelop.PutCoords(deviceRect.left, deviceRect.bottom, deviceRect.right, deviceRect.top);
                // 将打印像素范围 设置给输出对象
                pExport.PixelBounds = pDeviceEnvelop;

                // 设置跟踪取消对象
                ITrackCancel pCancle = new CancelTrackerClass();
                // 进行视图控件的视图输出操作，设置对应参数
                pageLyaoutCtrl.ActiveView.Output(pExport.StartExporting(), (int)pExport.Resolution, ref deviceRect, pageLyaoutCtrl.ActiveView.Extent, pCancle);
                pExport.FinishExporting();//完成输出
            }
            catch
            {

            }

        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
            moveToFeatures(listTargetValves);
        }

        private void listBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && listBox1.SelectedItems.Count != 0)
            {
                contextMenuStrip1.Show(Control.MousePosition);
            }
        }

        private void listBox2_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && listBox2.SelectedItems.Count != 0)
            {
                contextMenuStrip2.Show(Control.MousePosition);
            }
        }

        private void 设为失灵阀门ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeature selectedPoint = ((IShownValve)listBox1.SelectedValue).feature;
            IFeatureClass featureClass = (IFeatureClass)selectedPoint.Class;
            //设置失灵阀门标识其ENABLED属性为1，代表水流无法从这里截断

            //获取工作空间
            IDataset dataset = featureClass as IDataset;
            IWorkspace workspace = dataset.Workspace;
            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;
            workspaceEdit.StartEditing(false);
            workspaceEdit.StartEditOperation();
            //修改属性
            int fieldID = selectedPoint.Fields.FindField("ENABLED");
            selectedPoint.set_Value(fieldID, 1);
            selectedPoint.Store();
            //停止编辑
            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);

            burstAnalysis();
        }

        private void 修复失灵阀门ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeature selectedPoint = ((IShownValve)listBox2.SelectedValue).feature;
            IFeatureClass featureClass = (IFeatureClass)selectedPoint.Class;
            //设置失灵阀门标识其ENABLED属性为0，代表水流从这可以里截断

            //获取工作空间
            IDataset dataset = featureClass as IDataset;
            IWorkspace workspace = dataset.Workspace;
            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;
            workspaceEdit.StartEditing(false);
            workspaceEdit.StartEditOperation();
            //修改属性
            int fieldID = selectedPoint.Fields.FindField("ENABLED");
            selectedPoint.set_Value(fieldID, 0);
            selectedPoint.Store();
            //停止编辑
            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);

            burstAnalysis();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            burstAnalysis();
            toolStripStatusLabel1.Text = "";
        }

        /// <summary>
        /// 执行爆管分析
        /// </summary>
        private void burstAnalysis()
        {
            //如果没有爆管点，进行提示
            if (listEdgeFlags.Count == 0)
            {
                MessageBox.Show("请选择爆管点。");
                return;
            }
            try
            {
                //首先清除已有的分析结果
                ClearElements(axMapControl.ActiveView, "Result");
                listTargetValves.Clear();
                listFaultyValves.Clear();
                shownTargetValves.Clear();
                shownFaultyValves.Clear();

                
                //为追踪任务解决器设置发生爆管的管线
                IEdgeFlag[] arrayEdgeFlag = new IEdgeFlag[listEdgeFlags.Count];
                for (int j = 0; j < listEdgeFlags.Count; j++)
                {
                    arrayEdgeFlag[j] = listEdgeFlags[j];
                }
                traceFlowSolverGEN.PutEdgeOrigins(ref arrayEdgeFlag);
                //定义相关变量
                IEnumNetEID junctionEIDs = new EnumNetEIDArrayClass();
                IEnumNetEID edgeEIDs = new EnumNetEIDArrayClass();

                //进行连通性分析
                traceFlowSolverGEN.FindFlowElements(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctionsAndEdges,
                            out junctionEIDs, out edgeEIDs);

                //绘制结果
                DrawTraceResults(junctionEIDs, edgeEIDs, GetColorByRGBValue(250, 130, 71));

                //获取失灵阀门
                INetElements netElements = geometricNetwork.Network as INetElements;
                GetFaultyValves(junctionEIDs, netElements);

                //查询应当关闭的阀门元素
                traceFlowSolverGEN.FindFlowEndElements(esriFlowMethod.esriFMConnected, esriFlowElements.esriFEJunctionsAndEdges,
                            out junctionEIDs, out edgeEIDs);

                //对分析结果进行遍历和判断，如果是阀门则添加到应当关闭的阀门列表中         
                GetClosedValves(junctionEIDs, netElements);

                //生成分析结果
                generateResult();

                //更新布局视图
                updatePageLayout();

                //移动视图到所有目标阀门
                moveToFeatures(listTargetValves);

            }
            catch (Exception ex) { MessageBox.Show(ex.Message+ex.StackTrace); }
        }

        /// <summary>
        /// 生成分析结果
        /// </summary>
        private void generateResult()
        {
            start();  //formResult生成计算显示信息
        }

        /// <summary>
        /// 根据已分析得到的管点获取需要关闭的阀门。
        /// </summary>
        /// <param name="junctionEIDs">已得到的管点分析结果</param>
        /// <param name="netElements">所分析的逻辑网络</param>
        private void GetClosedValves(IEnumNetEID junctionEIDs, INetElements netElements)
        {
            //准备用来存储查询元素的变量
            int userClassID = 0;
            int userID = 0;
            int userSubID = 0;

            //初始化eid
            int eid = -1;

            //初始化管爆位置连通的节点
            int junctionNum = junctionEIDs.Count;
            junctionEIDs.Reset();

            //遍历连通的管点，如果是阀门，存储
            for (int i = 0; i < junctionNum; i++)
            {
                //eid指向下一位
                eid = junctionEIDs.Next();
                //根据eid查询userClassID、userID、userSubID
                netElements.QueryIDs(eid, esriElementType.esriETJunction, out userClassID, out userID, out userSubID);
                //获取该对象
                IFeature feature = GetFeatureClassByID(userClassID, axMapControl.Map).GetFeature(userID);
                //获取该对象的附属物字段
                string subs = ConfigurationManager.AppSettings[5];
                string subsID = feature.get_Value(feature.Fields.FindField(subs)).ToString();

                //如果userClassID代表阀门
                if (subsID == "阀门")
                {
                    //应关闭阀门列表添加改阀门元素
                    listTargetValves.Add(feature);

                    /**
                    //添加标记样式
                    ISimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbolClass();
                    simpleMarkerSymbol.Color = FormMain.GetColorByRGBValue(255, 0, 0);
                    simpleMarkerSymbol.Size = 18;
                    simpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSCross;

                    //设置应关闭阀门的地图元素
                    ESRI.ArcGIS.Carto.IElement element = new MarkerElementClass();
                    element.Geometry = feature.Shape;
                    ((IMarkerElement)element).Symbol = simpleMarkerSymbol;
                    ((IElementProperties)element).Name = "Result";

                    //添加目标阀门的地图元素，并进行刷新
                    ((IGraphicsContainer)axMapControl.ActiveView).AddElement(element, 0);
                    axMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, axMapControl.ActiveView.Extent);
                    **/
                }

            }
        }

        /// <summary>
        /// 筛选失灵阀门
        /// </summary>
        /// <param name="junctionEIDs">已得到的管点分析结果</param>
        /// <param name="netElements">所分析的逻辑网络</param>
        private void GetFaultyValves(IEnumNetEID junctionEIDs, INetElements netElements)
        {
            //准备用来存储查询元素的变量
            int userClassID = 0;
            int userID = 0;
            int userSubID = 0;

            //初始化eid
            int eid = -1;

            //初始化管爆位置连通的节点
            int junctionNum = junctionEIDs.Count;
            junctionEIDs.Reset();

            //遍历连通的管点，如果是阀门，存储
            for (int i = 0; i < junctionNum; i++)
            {
                //eid指向下一位
                eid = junctionEIDs.Next();
                //根据eid查询userClassID、userID、userSubID
                netElements.QueryIDs(eid, esriElementType.esriETJunction, out userClassID, out userID, out userSubID);
                //获取该对象
                IFeature feature = GetFeatureClassByID(userClassID, axMapControl.Map).GetFeature(userID);
                //获取该对象的附属物字段
                string subs = ConfigurationManager.AppSettings[5];
                string subsID = feature.get_Value(feature.Fields.FindField(subs)).ToString();

                //如果userClassID代表阀门
                if (subsID == "阀门")
                {
                    //应关闭阀门列表添加改阀门元素
                    listFaultyValves.Add(feature);
                }
            }
        }

        /// <summary>
        /// 根据R、G、B值获取IColor接口的颜色变量。
        /// </summary>
        /// <param name="red">R分量值</param>
        /// <param name="green">G分量值</param>
        /// <param name="blue">B分量值</param>
        /// <returns>IColor接口的颜色变量</returns>
        public static IColor GetColorByRGBValue(int red, int green, int blue)
        {
            IRgbColor rgbColor = new RgbColorClass
            {
                Red = red,
                Green = green,
                Blue = blue
            };
            return rgbColor;
        }

        /// <summary>
        /// 根据设定的颜色绘制网络分析结果中的管点和管线
        /// </summary>
        /// <param name="junctionEIDs">分析结果管点</param>
        /// <param name="edgeEIDs">分析结果管线</param>
        /// <param name="color">设定的颜色</param>
        private void DrawTraceResults(IEnumNetEID junctionEIDs, IEnumNetEID edgeEIDs, IColor color)
        {
            INetElements netElements = geometricNetwork.Network as INetElements;
            int userClassID = -1;
            int userID = -1;
            int userSubID = -1;
            int eid = -1;
            IFeature feature;
            IFeatureClass featureClass;
            //设置管点和管线显示的Symbol
            ISimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbolClass
            {
                Color = color,
                Size = 6,
                Style = esriSimpleMarkerStyle.esriSMSCircle
            };
            ISimpleLineSymbol simpleLineSymbol = new SimpleLineSymbolClass
            {
                Color = color,
                Width = 2,
                Style = esriSimpleLineStyle.esriSLSSolid
            };
            ESRI.ArcGIS.Carto.IElement element;
            //如果分析结果中包含管点，则查询其对应的空间要素并绘制
            if (junctionEIDs != null)
            {
                for (int i = 0; i < junctionEIDs.Count; i++)
                {
                    eid = junctionEIDs.Next();
                    netElements.QueryIDs(eid, esriElementType.esriETJunction, out userClassID, out userID, out userSubID);
                    featureClass = GetFeatureClassByID(userClassID, axMapControl.Map);
                    if (featureClass != null)
                    {
                        feature = featureClass.GetFeature(userID);

                        element = new MarkerElementClass
                        {
                            Geometry = feature.Shape
                        };
                        ((IMarkerElement)element).Symbol = simpleMarkerSymbol;
                        ((IElementProperties)element).Name = "Result";
                        ((IGraphicsContainer)axMapControl.ActiveView).AddElement(element, 0);
                    }
                }
            }

            //如果分析结果中包含管线，则查询其对应的空间要素并绘制
            if (edgeEIDs != null)
            {
                for (int i = 0; i < edgeEIDs.Count; i++)
                {
                    eid = edgeEIDs.Next();
                    netElements.QueryIDs(eid, esriElementType.esriETEdge, out userClassID, out userID, out userSubID);
                    featureClass = GetFeatureClassByID(userClassID, axMapControl.Map);
                    feature = featureClass.GetFeature(userID);

                    element = new LineElementClass
                    {
                        Geometry = feature.Shape
                    };
                    ((ILineElement)element).Symbol = simpleLineSymbol;
                    ((IElementProperties)element).Name = "Result";
                    ((IGraphicsContainer)axMapControl.ActiveView).AddElement(element, 0);
                }
            }
            //刷新地图中的图形
            axMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, axMapControl.ActiveView.Extent);
        }

        /// <summary>
        /// 根据FeatureClass的ID在当前地图中获取FeatureClass。
        /// </summary>
        /// <param name="userClassID">FeatureClass的ID</param>
        /// <param name="map">当前地图</param>
        /// <returns>IFeatureClass接口的变量，或为空</returns>
        private IFeatureClass GetFeatureClassByID(int userClassID, IMap map)
        {
            IFeatureClass featureClass = null;
            for (int i = 0; i < map.LayerCount; i++)
            {
                featureClass = ((IFeatureLayer)map.get_Layer(i)).FeatureClass;
                if (featureClass.FeatureClassID == userClassID)
                {
                    return featureClass;
                }
            }
            //找不到，返回空
            return null;
        }

        /// <summary>
        /// 根据Element名称清除当前视图中的Element
        /// </summary>
        /// <param name="activeView">当前视图</param>
        /// <param name="elementName">Element的名称</param>
        private void ClearElements(IActiveView activeView, string elementName)
        {
            //重置当前视图的指针
            IGraphicsContainer graphicsContainer = activeView as IGraphicsContainer;
            graphicsContainer.Reset();
            ESRI.ArcGIS.Carto.IElement element = graphicsContainer.Next();

            //遍历视图的所有元素，查看是否是需要删除的元素，是则删除
            while (element != null)
            {
                if (((IElementProperties)element).Name == elementName)
                {
                    graphicsContainer.DeleteElement(element);
                }

                element = graphicsContainer.Next();
            }

            //刷新
            activeView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, activeView.Extent);
        }

        /// <summary>
        /// 渲染列表中的阀门，使显示名字
        /// </summary>
        /// <param name="valves"></param>
        private void renderValves(List<IFeature> valves)
        {
            for (int i = 0; i < valves.Count; i++)
            {
                //获取阀门对象
                IFeature feature = valves[i];
                //获取阀门名称对应字段名
                string fieldName = ConfigurationManager.AppSettings.Get("valveName");
                string valveName = feature.get_Value(feature.Fields.FindField(fieldName)).ToString();

                //设置文本标签
                ITextSymbol textSymbol = new TextSymbolClass();
                stdole.StdFont myFont = new stdole.StdFontClass
                {
                    Name = "宋体",
                    Size = 24
                };
                textSymbol.Font = (stdole.IFontDisp)myFont;
                textSymbol.Angle = 0;
                //垂直方向与基线对齐
                textSymbol.VerticalAlignment = esriTextVerticalAlignment.esriTVABaseline;
                //文本两端对齐
                textSymbol.HorizontalAlignment = esriTextHorizontalAlignment.esriTHAFull;
                textSymbol.Text = valveName;
                textSymbol.Color = GetColorByRGBValue(160, 32, 240);
                ITextElement textElement = new TextElementClass
                {
                    Symbol = textSymbol,
                    Text = textSymbol.Text
                };
                //将文本添加到阀门位置
                ESRI.ArcGIS.Carto.IElement element = (ESRI.ArcGIS.Carto.IElement)textElement;
                element.Geometry = feature.Shape;
                ((IElementProperties)element).Name = "Result";
                axMapControl.ActiveView.GraphicsContainer.AddElement(element, 0);
                axMapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, element, null);


            }
        }

        /// <summary>
        /// 给页面布局控件添加标题
        /// </summary>
        /// <param name="pageLayout"></param>
        public static void InsertTitle(AxPageLayoutControl axPageLayoutControl)
        {
            //找到PageLayout
            IPageLayout pPageLayout = axPageLayoutControl.PageLayout;
            //找到元素容器
            IGraphicsContainer pGraphicsContainer = pPageLayout as IGraphicsContainer;
            //创建元素
            ITextElement pTextElement = new TextElementClass
            {
                Text = "爆管分析结果"
            };
            ITextSymbol pTextSymbol = new TextSymbolClass
            {
                Size = 40,
                Color = GetColorByRGBValue(0, 0, 0)
            };
            pTextElement.Symbol = pTextSymbol;
            //设置位置                        
            ESRI.ArcGIS.Carto.IElement pElement = pTextElement as ESRI.ArcGIS.Carto.IElement;

            IMapFrame pMapFrame = pGraphicsContainer.FindFrame(axPageLayoutControl.ActiveView.FocusMap) as IMapFrame;
            ESRI.ArcGIS.Carto.IElement mapElement = pMapFrame as ESRI.ArcGIS.Carto.IElement;
            IEnvelope mapEnv = mapElement.Geometry.Envelope;
            IEnvelope pEnv = new EnvelopeClass();
            pEnv.PutCoords(mapEnv.XMax, mapEnv.YMax, mapEnv.XMax - 27, mapEnv.YMax - 12);
            pElement.Geometry = pEnv;
            //将元素添加到容器中
            pGraphicsContainer.AddElement(pElement, 0);
            //刷新
            axPageLayoutControl.Refresh();
        }

        public void AddScalebar(AxPageLayoutControl axPageLayoutControl)
        {
            IGraphicsContainer container = axPageLayoutControl.PageLayout as IGraphicsContainer;
            IActiveView activeView = axPageLayoutControl.PageLayout as IActiveView;
            // 获得MapFrame  
            IFrameElement frameElement = container.FindFrame(activeView.FocusMap);
            IMapFrame mapFrame = frameElement as IMapFrame;
            //根据MapSurround的uid，创建相应的MapSurroundFrame和MapSurround  
            UID uid = new UIDClass
            {
                Value = "esriCarto.AlternatingScaleBar"
            };
            IMapSurroundFrame mapSurroundFrame = mapFrame.CreateSurroundFrame(uid, null);
            //设置MapSurroundFrame中比例尺的样式  
            IMapSurround mapSurround = mapSurroundFrame.MapSurround;
            IScaleBar markerScaleBar = ((IScaleBar)mapSurround);
            markerScaleBar.LabelPosition = esriVertPosEnum.esriBelow;
            markerScaleBar.UseMapSettings();
            //QI，确定mapSurroundFrame的位置  
            ESRI.ArcGIS.Carto.IElement element = mapSurroundFrame as ESRI.ArcGIS.Carto.IElement;
            IEnvelope envelope = new EnvelopeClass();
            envelope.PutCoords(1, 1, 10, 2);
            element.Geometry = envelope;
            //使用IGraphicsContainer接口添加显示  
            container.AddElement(element, 0);
            activeView.Refresh();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            //初始化爆管点选择工具
            ToolAddBurstPipe toolAddEdgeFlag = new ToolAddBurstPipe
            {
                ListEdgeFlags = listEdgeFlags,
                GeometricNetwork = geometricNetwork,
                burstPoints = burstPoints,
                addressList = addressList
            };
            toolAddEdgeFlag.OnCreate(axMapControl.Object);

            //绑定爆管点工具与地图控件
            axMapControl.CurrentTool = toolAddEdgeFlag;

            //状态栏提示
            toolStripStatusLabel1.Text = "请选择爆管的管线";
        }

        //双击设为失灵阀门
        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            IFeature selectedPoint = ((IShownValve)listBox1.SelectedValue).feature;
            IFeatureClass featureClass = (IFeatureClass)selectedPoint.Class;
            //设置失灵阀门标识其ENABLED属性为1，代表水流无法从这里截断

            //获取工作空间
            IDataset dataset = featureClass as IDataset;
            IWorkspace workspace = dataset.Workspace;
            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;
            workspaceEdit.StartEditing(false);
            workspaceEdit.StartEditOperation();
            //修改属性
            int fieldID = selectedPoint.Fields.FindField("ENABLED");
            selectedPoint.set_Value(fieldID, 1);
            selectedPoint.Store();
            //停止编辑
            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);

            //移动所选阀门位置
            listTargetValves.Remove(selectedPoint);
            listFaultyValves.Add(selectedPoint);

            //重新生成listBox
            start();
        }

        /// <summary>
        /// 双击设为正常阀门
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBox2_DoubleClick(object sender, EventArgs e)
        {
            IFeature selectedPoint = ((IShownValve)listBox2.SelectedValue).feature;
            IFeatureClass featureClass = (IFeatureClass)selectedPoint.Class;
            //设置失灵阀门标识其ENABLED属性为0，代表水流从这可以里截断

            //获取工作空间
            IDataset dataset = featureClass as IDataset;
            IWorkspace workspace = dataset.Workspace;
            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;
            workspaceEdit.StartEditing(false);
            workspaceEdit.StartEditOperation();
            //修改属性
            int fieldID = selectedPoint.Fields.FindField("ENABLED");
            selectedPoint.set_Value(fieldID, 0);
            selectedPoint.Store();
            //停止编辑
            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);

            //移动所选阀门位置
            listFaultyValves.Remove(selectedPoint);
            listTargetValves.Add(selectedPoint);

            //重新生成listBox
            start();

        }


        public void updatePageLayout()
        {
            axPageLayoutControl.ActiveView.Clear();
            CopyMapFromMapControlToPageLayoutControl();
        }

        private void CopyMapFromMapControlToPageLayoutControl()
        {
            //获得IObjectCopy接口
            IObjectCopy pObjectCopy = new ObjectCopyClass();
            //获得要拷贝的图层 
            object pSourceMap = axMapControl.Map;
            //获得拷贝图层
            object pCopiedMap = pObjectCopy.Copy(pSourceMap);
            //获得要重绘的地图 
            object pOverwritedMap = axPageLayoutControl.ActiveView.FocusMap;
            //重绘pagelayout地图
            pObjectCopy.Overwrite(pCopiedMap, ref pOverwritedMap);
            //生成图例
            InsertNorth(axPageLayoutControl);
            makeLegend(axPageLayoutControl.ActiveView, axPageLayoutControl.PageLayout);
            axPageLayoutControl.PageLayout.ZoomToWhole();
        }

        /// <summary>
        /// 生成图例
        /// </summary>
        private void makeLegend(IActiveView activeView, IPageLayout pageLayout)
        {
            UID id = new UID
            {
                Value = "esriCarto.Legend"
            };
            IGraphicsContainer graphicsContainer = pageLayout as IGraphicsContainer;
            IMapFrame mapFrame = graphicsContainer.FindFrame(activeView.FocusMap) as IMapFrame;
            //根据唯一标识符，创建与之对应的MapSurroundFrame
            IMapSurroundFrame mapSurroundFrame = mapFrame.CreateSurroundFrame(id, null);
            //获取pageLayout中的图例元素

            // ESRI.ArcGIS.Carto.IElement element = null;

            //设置MapSurroundFrame背景
            ISymbolBackground symbolBackground = new SymbolBackgroundClass();
            IFillSymbol fillSymbol = new SimpleFillSymbolClass();
            ILineSymbol lineSymbol = new SimpleLineSymbolClass
            {
                Color = GetColorByRGBValue(0, 0, 1)
            };
            fillSymbol.Color = GetColorByRGBValue(240, 240, 240);
            fillSymbol.Outline = lineSymbol;
            symbolBackground.FillSymbol = fillSymbol;
            mapSurroundFrame.Background = symbolBackground;
            //添加图例
            ESRI.ArcGIS.Carto.IElement pElement = mapSurroundFrame as ESRI.ArcGIS.Carto.IElement;
            //设置图例包络线
            IEnvelope envelope = new EnvelopeClass();
            //通过当前地图框架得到相对位置
            ESRI.ArcGIS.Carto.IElement mapElement = mapFrame as ESRI.ArcGIS.Carto.IElement;
            IEnvelope mapEnv = mapElement.Geometry.Envelope;
            envelope.PutCoords(mapEnv.XMax - 2.55, mapEnv.YMin + 0.05, mapEnv.XMax, mapEnv.YMin + 1.2);
            pElement.Geometry = envelope;
            ((IElementProperties)pElement).Name = "Result";
            IMapSurround mapSurround = mapSurroundFrame.MapSurround;
            ILegend legend = mapSurround as ILegend;
            legend.ClearItems();
            legend.Format.DefaultPatchHeight = legend.Format.DefaultPatchHeight;
            legend.Format.DefaultPatchWidth = legend.Format.DefaultPatchHeight;
            if (legend.Title == null)
            {
                legend.Title = "图例";
            }
            for (int i = 0; i < activeView.FocusMap.LayerCount; i++)
            {
                try
                {
                    ILegendItem legendItem = new HorizontalLegendItemClass
                    {
                        Layer = activeView.FocusMap.get_Layer(i),//获取添加图例关联图层
                        ShowDescriptions = true,
                        Columns = 1,
                        ShowHeading = true,
                        ShowLabels = true
                    };
                    legend.AddItem(legendItem);//添加图例内容
                }
                catch { }

            }

            graphicsContainer.AddElement(pElement, 0);
            activeView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);


        }

        /// <summary>
        /// 给页面布局控件添加指北针
        /// </summary>
        /// <param name="pageLayout"></param>
        public static void InsertNorth(AxPageLayoutControl axPageLayout)
        {
            ESRI.ArcGIS.Carto.IElement pElement = axPageLayout.FindElementByName("MarkerNorthArrow");
            if (pElement != null)
            {
                axPageLayout.ActiveView.GraphicsContainer.DeleteElement(pElement);  //删除已经存在的图例
            }
            IPageLayout pPageLayout = axPageLayout.PageLayout;
            IGraphicsContainer pGraphicsContainer = pPageLayout as IGraphicsContainer;
            IActiveView pActiveView = pPageLayout as IActiveView;
            UID pID = new UIDClass
            {
                Value = "esriCore.MarkerNorthArrow"
            };

            IMapFrame pMapFrame = pGraphicsContainer.FindFrame(pActiveView.FocusMap) as IMapFrame;
            if (pMapFrame == null)
            {
                return;
            }

            IMapSurroundFrame pMapSurroundFrame = pMapFrame.CreateSurroundFrame(pID, null);
            if (pMapSurroundFrame == null)
            {
                return;
            }

            ESRI.ArcGIS.Carto.IElement mapElement = pMapFrame as ESRI.ArcGIS.Carto.IElement;
            IEnvelope mapEnv = mapElement.Geometry.Envelope;
            IEnvelope pEnv = new EnvelopeClass();
            pEnv.PutCoords(mapEnv.XMax, mapEnv.YMax, mapEnv.XMax - 3, mapEnv.YMax - 3);
            pElement = (ESRI.ArcGIS.Carto.IElement)pMapSurroundFrame;
            pElement.Geometry = pEnv;
            pMapSurroundFrame.MapSurround.Name = "MarkerNorthArrow";
            INorthArrow pNorthArrow = pMapSurroundFrame.MapSurround as INorthArrow;
            pGraphicsContainer.AddElement(pElement, 0);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            ClearElements(axMapControl.ActiveView, "BurstPipePoint");
            timer2.Enabled = true;
            timer1.Enabled = false;
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            DrawBurstPipePoint(axMapControl.ActiveView, "BurstPipePoint", burstPoints);
            timer2.Enabled = false;
            timer1.Enabled = true;
        }

        /// <summary>
        /// 绘制爆管点
        /// </summary>
        /// <param name="activeView">当前视图</param>
        /// <param name="elementName">Element的名称</param>
        private void DrawBurstPipePoint(IActiveView activeView, string elementName, List<IPoint> burstPoints)
        {
            for (int i = 0; i < burstPoints.Count; i++)
            {
                //绘制并显示管线标识
                ICharacterMarkerSymbol characterMarkerSymbol = new CharacterMarkerSymbol
                {
                    CharacterIndex = 68,
                    Size = 30,
                    Color = GetColorByRGBValue(255, 0, 0)
                };


                ESRI.ArcGIS.Carto.IElement element = new MarkerElementClass
                {
                    Geometry = burstPoints[i]
                };
                ((IMarkerElement)element).Symbol = characterMarkerSymbol;
                ((IElementProperties)element).Name = elementName;
                ((IGraphicsContainer)activeView).AddElement(element, 0);

                activeView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, activeView.Extent);
            }

        }

        /// <summary>
        /// 绘制感兴趣的阀门
        /// </summary>
        /// <param name="activeView">当前视图</param>
        /// <param name="elementName">Element的名称</param>
        private void DrawValvePoint(IActiveView activeView, string elementName, List<IFeature> listValves)
        {
            for (int i = 0; i < listValves.Count; i++)
            {

                //绘制并显示管线标识
                ICharacterMarkerSymbol characterMarkerSymbol = new CharacterMarkerSymbol
                {
                    CharacterIndex = 46,
                    Size = 35,
                    Color = GetColorByRGBValue(160, 32, 240)
                };

                ESRI.ArcGIS.Carto.IElement element = new MarkerElementClass
                {
                    Geometry = listValves[i].Shape
                };
                ((IMarkerElement)element).Symbol = characterMarkerSymbol;
                ((IElementProperties)element).Name = elementName;
                ((IGraphicsContainer)activeView).AddElement(element, 0);
                activeView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, activeView.Extent);
            }

        }

        /// <summary>
        /// //根据shownTargetValves和shownFaultyValves生成显示数据
        /// </summary>
        public void generateDataGridView()
        {
            dataGridView1.Columns.Clear();       //清空列表
            dataGridView1.AutoGenerateColumns = false;     // 防止自由生成所有数据列
            int index = 0;    // 初始化下标
            //生成表格的字段（对应表格的列）
            foreach (KeyValuePair<string, string> entry in shownPropMap)   //遍历需要展示的属性
            {
                dataGridView1.Columns.Add(entry.Key, entry.Value);              // 添加新的列
                dataGridView1.Columns[index].DataPropertyName = entry.Key;      // 设置改列对应的属性
                index++;                                                        // 移动下标
            }
            //更新数据源，添加记录（对应表格每行的数据）
            dataGridView1.DataSource = new BindingSource(new BindingList<IShownValve>(shownTargetValves.Union(shownFaultyValves).ToList<IShownValve>()), null);
            //设置首列宽度
            dataGridView1.RowHeadersWidth = 25;
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            burstAnalysis();
            toolStripStatusLabel1.Text = "请选择爆管的管线";
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            //初始化爆管点选择工具
            ToolSetFaultyValve toolAddFaultyValve = new ToolSetFaultyValve
            {
                GeometricNetwork = geometricNetwork,
                ActiveView = axMapControl.ActiveView,
                Map = axMapControl.Map,
                formResult = this
            };
            toolAddFaultyValve.OnCreate(axMapControl.Object);

            //绑定爆管点工具与地图控件
            axMapControl.CurrentTool = toolAddFaultyValve;

            //状态栏提示
            toolStripStatusLabel1.Text = "请在地图上选择正常工作的阀门设为失灵";
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            //初始化爆管点选择工具
            ToolFixFaultyValve toolFixFaultyValve = new ToolFixFaultyValve
            {
                GeometricNetwork = geometricNetwork,
                ActiveView = axMapControl.ActiveView,
                Map = axMapControl.Map,
                formResult = this
            };
            toolFixFaultyValve.OnCreate(axMapControl.Object);

            //绑定爆管点工具与地图控件
            axMapControl.CurrentTool = toolFixFaultyValve;

            //状态栏提示
            toolStripStatusLabel1.Text = "请在地图上选择失灵的阀门设为正常阀门";
        }

        /// <summary>
        /// 清空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            //清空数据
            listTargetValves.Clear();
            listFaultyValves.Clear();
            burstPoints.Clear();
            listEdgeFlags.Clear();
            listJunctionFlags.Clear();
            addressList.Clear();

            //重新生成结果窗体
            start();
            dataGridView1.Columns.Clear();
            ClearElements(axMapControl.ActiveView, "Result");
        }

        /// <summary>
        /// 参考IShownValve中的属性，手动生成属性中英文映射
        /// </summary>
        private void generatePropMap()
        {
            //新建字典
            propMap = new Dictionary<string, string>
            {
                { "ObjectID", "阀门ID" },
                { "Name", "阀门名称" },
                { "X", "X坐标" },
                { "Y", "Y坐标" },
                { "OwnerDept", "所属公司" },
                { "SurveyDept", "勘测单位" },
                { "Type", "阀门类型" },
                { "RepairCount", "维修次数" }
            };

        }

        private void timer3_Tick(object sender, EventArgs e)
        {

            ClearElements(axMapControl.ActiveView, "Valve");
            timer4.Enabled = true;
            timer3.Enabled = false;

        }

        private void timer4_Tick(object sender, EventArgs e)
        {
            DrawValvePoint(axMapControl.ActiveView, "Valve", listTargetValves);
            DrawValvePoint(axMapControl.ActiveView, "Valve", listFaultyValves);
            timer4.Enabled = false;
            timer3.Enabled = true;
        }

        private void FormResult_FormClosing(object sender, FormClosingEventArgs e)
        {
            //清空数据
            listTargetValves.Clear();
            listFaultyValves.Clear();
            burstPoints.Clear();
            listEdgeFlags.Clear();
            listJunctionFlags.Clear();

            //重新生成结果窗体
            ClearElements(axMapControl.ActiveView, "Result");
            ClearElements(axMapControl.ActiveView, "BurstPipePoint");
            ClearElements(axMapControl.ActiveView, "Valve");
        }

        private void label3_Click(object sender, EventArgs e)
        {
            FormFilter filter = new FormFilter
            {
                StartPosition = FormStartPosition.CenterScreen,//窗体居中
                TopMost = true, //窗体置顶
                formResult = this
            }; //生成窗体
            filter.start();
            filter.Show();
        }
    }

}
